package teamgodeater.hicarnet.MVP.Ui.Main;

import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.amberwhitesky.dialog.CustomDialog;
import com.rey.material.widget.FloatingActionButton;

import org.angmarch.views.NiceSpinner;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.codetail.animation.SupportAnimator;
import io.codetail.animation.ViewAnimationUtils;
import teamgodeater.hicarnet.C;
import teamgodeater.hicarnet.Data.GasStationData;
import teamgodeater.hicarnet.Data.UserOrderData;
import teamgodeater.hicarnet.Help.RestClientHelp;
import teamgodeater.hicarnet.Help.UserDataHelp;
import teamgodeater.hicarnet.Layout.LoadingView.BookLoadingViewHelp;
import teamgodeater.hicarnet.MVP.Base.BaseFragment;
import teamgodeater.hicarnet.MVP.Base.WindowsParams;
import teamgodeater.hicarnet.R;
import teamgodeater.hicarnet.RestClient.RestClient;
import teamgodeater.hicarnet.Utils.Utils;
import teamgodeater.hicarnet.Widget.RippleBackGroundView;


/**
 * Created by G on 2016/6/22 0022.
 */

public class BuyFragment extends BaseFragment {

    @Bind(R.id.money)
    TextView money;
    @Bind(R.id.petrolGage)
    TextView petrolGage;
    @Bind(R.id.moneySeekBar)
    SeekBar moneySeekBar;
    @Bind(R.id.addOrder)
    FloatingActionButton addOrder;
    @Bind(R.id.close)
    FloatingActionButton close;
    @Bind(R.id.gasType)
    NiceSpinner gasType;
    @Bind(R.id.gasKind)
    NiceSpinner gasKind;
    @Bind(R.id.constraintLayout)
    ConstraintLayout constraintLayout;
    @Bind(R.id.title)
    TextView title;

    float price = 0;
    @Bind(R.id.succeedFace)
    ImageView succeedFace;
    @Bind(R.id.succeedGo)
    RippleBackGroundView succeedGo;
    @Bind(R.id.succeedBack)
    RippleBackGroundView succeedBack;
    @Bind(R.id.succeedLayout)
    FrameLayout succeedLayout;

    private GasStationData.ResultBean.DataBean data;
    private BookLoadingViewHelp bookLoadingViewHelp;

    @Override
    public void onOnceGlobalLayoutListen() {
        int width = mTopView.getWidth();
        int height = mTopView.getHeight();
        int maxRadius = (int) Math.sqrt(width * width + height * height);

        SupportAnimator circularReveal = ViewAnimationUtils.createCircularReveal(mTopView, width / 2, height - Utils.dp2Px(60), 0, maxRadius);
        circularReveal.setInterpolator(new AccelerateInterpolator());
        circularReveal.setDuration(500L);
        circularReveal.start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public String getType() {
        return C.VT_MAIN;
    }

    @NonNull
    @Override
    protected WindowsParams onCreateSupportViewParams(WindowsParams windowsParams) {
        windowsParams.rootLayoutId = R.layout.frgm_buy;
        windowsParams.isHasToolBar = false;
        windowsParams.isNoFullScreen = false;
        return windowsParams;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, mRootContain);
        setColor();
        setListener();
        setView();
        bookLoadingViewHelp = new BookLoadingViewHelp(constraintLayout);
        return rootView;
    }

    private void setColor() {
        succeedFace.setColorFilter(Utils.getColorFromRes(R.color.colorGreen), PorterDuff.Mode.SRC_IN);
        addOrder.getIcon().mutate().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
        close.getIcon().mutate().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
    }

    private void setListener() {
        succeedBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        succeedGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.toast("Go");
            }
        });

        gasType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setGasKind(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        gasKind.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view;
                String string = tv.getText().toString();
                setPrice(string);
                setTipView(moneySeekBar.getProgress());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        moneySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                setTipView(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        addOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomDialog customDialog = new CustomDialog(getContext(), R.layout.customdialog);
                customDialog.setListener(new CustomDialog.InputDialogListener() {
                    @Override
                    public void onOK(String text) {
                        addOrder();
                    }
                });
                customDialog.show();
            }
        });
    }

    private void addOrder() {
        UserOrderData userOrderData = new UserOrderData();
        userOrderData.setGas_name(data.getName());
        userOrderData.setGas_address(data.getAddress());
        userOrderData.setIs_used(false);
        userOrderData.setLat(Double.parseDouble(data.getLat()));
        userOrderData.setLon(Double.parseDouble(data.getLon()));
        userOrderData.setType(gasType.getText().toString());
        userOrderData.setKind(gasKind.getText().toString());
        String ms = money.getText().toString();
        String trim = ms.substring(0, ms.length() - 3).trim();
        userOrderData.setMoney(Float.parseFloat(trim));
        String ps = petrolGage.getText().toString();
        String trim1 = ps.substring(0, ms.length() - 3).trim();
        userOrderData.setRise(Float.parseFloat(trim1));
        userOrderData.setPrice(price);
        final RestClientHelp restClientHelp = new RestClientHelp();
        bookLoadingViewHelp.startAnimator("正在提交订单数据 请稍后...");
        restClientHelp.addUserOder(userOrderData, new RestClient.OnResultListener<String>() {
            @Override
            public void succeed(String bean) {
                succeedAddOrder();
                bookLoadingViewHelp.startAnimator("提交订单成功\n等待服务器返回结果 请稍后...");
            }

            @Override
            public void error(int code) {
                bookLoadingViewHelp.stopAnimator();
                RestClientHelp.generalErrorToast(code);
            }
        });
    }

    private void succeedAddOrder() {
        RestClientHelp restClientHelp = new RestClientHelp();
        restClientHelp.getUserOrder(new RestClient.OnResultListener<List<UserOrderData>>() {
            @Override
            public void succeed(List<UserOrderData> bean) {
                showResult();
                UserDataHelp.getUserOrderDatas(null);
            }

            @Override
            public void error(int code) {
                showResult();
            }
        });
    }

    private void showResult() {
        succeedLayout.setVisibility(View.VISIBLE);
        title.setText("支付成功");
        Utils.toast("支付成功");
        bookLoadingViewHelp.stopAnimator();
    }

    private void setPrice(String string) {
        int i = string.indexOf("   ");
        int i1 = string.indexOf("元/升");
        String pritext = string.substring(i, i1);
        price = Float.parseFloat(pritext.trim());
    }

    private void setTipView(int progress) {
        DecimalFormat format = new DecimalFormat("#.0");
        money.setText(format.format(price * progress) + "  元");
        petrolGage.setText(format.format(0.5 * progress) + "  升");
    }

    private void setView() {
        succeedLayout.setVisibility(View.GONE);
        moneySeekBar.setMax(200);
        moneySeekBar.setProgress(50);
        setGasType();
        setGasKind(0);
    }

    private void setGasType() {
        List<String> dataset = new ArrayList<>();
        dataset.add("汽油");
        dataset.add("柴油");
        gasType.attachDataSource(dataset);
    }

    private void setGasKind(int index) {
        List<String> dataset = new ArrayList<>();
        GasStationData.ResultBean.DataBean.GastpriceBean gastprice = data.getGastprice();
        GasStationData.ResultBean.DataBean.PriceBean priceBean = data.getPrice();
        if (index == 0) {
            if (gastprice.getE90() != null)
                dataset.add("#90    " + gastprice.getE90() + " 元/升(省控)");
            else
                dataset.add("#90    " + priceBean.getE0() + " 元/升(打折)");
            if (gastprice.getE92() != null)
                dataset.add("#92    " + gastprice.getE92() + " 元/升(省控)");
            if (gastprice.getE93() != null)
                dataset.add("#93    " + gastprice.getE93() + " 元/升(省控)");
            else
                dataset.add("#93    " + priceBean.getE93() + " 元/升(打折)");
            if (gastprice.getE95() != null)
                dataset.add("#95    " + gastprice.getE95() + " 元/升(省控)");
            if (gastprice.getE97() != null)
                dataset.add("#97    " + gastprice.getE97() + " 元/升(省控)");
            else
                dataset.add("#97    " + priceBean.getE97() + " 元/升(打折)");

        } else {
            if (gastprice.getE0() != null) {
                dataset.add("#0    " + gastprice.getE0() + " 元/升(省控)");
            } else {
                dataset.add("#0    " + priceBean.getE0() + " 元/升(打折)");
            }
        }
        gasKind.attachDataSource(dataset);
        gasKind.setSelectedIndex(dataset.size() - 1);
        setPrice(dataset.get(dataset.size() - 1));
        setTipView(moneySeekBar.getProgress());
    }

    @Override
    public void onToolBarClick(View v, String tag) {
        if (tag.equals("back")) {
            finish();
        }
    }

    @Override
    public boolean onInterceptBack() {
        finish();
        return true;
    }

    boolean isFinish = false;

    private void finish() {
        if (isFinish)
            return;
        isFinish = true;
        destroySelfShowBefore(490L);
        int width = mTopView.getWidth();
        int height = mTopView.getHeight();
        int maxRadius = (int) Math.sqrt(width * width + height * height);

        SupportAnimator circularReveal = ViewAnimationUtils.createCircularReveal(mTopView, width / 2, height - Utils.dp2Px(60), maxRadius, 0);
        circularReveal.setInterpolator(new AccelerateInterpolator());
        circularReveal.setDuration(500L);
        circularReveal.start();
    }

    public void setData(GasStationData.ResultBean.DataBean data) {
        this.data = data;
    }


}
